package per.turtle.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import per.turtle.common.core.constant.CommonConstants;
import per.turtle.common.core.constant.UserConstants;
import per.turtle.common.core.exception.BaseException;
import per.turtle.common.core.utils.SecurityUtils;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.system.dto.LoginUser;
import per.turtle.system.entity.SysUser;
import per.turtle.system.feign.RemoteLogService;
import per.turtle.system.feign.RemoteUserService;

/**
 * 登录校验方法
 *
 * @author turtle
 */
@Component
@RequiredArgsConstructor
public class SysLoginService {

    private final RemoteLogService remoteLogService;

    private final RemoteUserService remoteUserService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtil.hasBlank(username, password)) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "用户密码长度不在指定范围");
            throw new BaseException("用户密码长度不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "用户名长度不在指定范围");
            throw new BaseException("用户名长度不在指定范围");
        }
        // 查询用户信息
        CommonResult<LoginUser> userResult = remoteUserService.getUserInfo(username);

        LoginUser userInfo = userResult.getData();
        if (BeanUtil.isEmpty(userInfo)) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("用户不存在/密码错误");
        }
        SysUser user = userInfo.getSysUser();
        if (user.getIsDisabled()) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号【" + username + "】已被停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户不存在/密码错误");
        }
        remoteLogService.saveLoginInfo(username, CommonConstants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public void logout(String loginName) {
        remoteLogService.saveLoginInfo(loginName, CommonConstants.LOGOUT, "退出成功");
    }

}